LIKE 操作符
发表于 2018-3-6 08:11:58 | 分类于 SQL |
LIKE 操作符
LIKE 操作符用于在 WHERE 子句中搜索列中的指定模式。
语法
SELECT column_name(s)
FROM table_name
WHERE column_name LIKE pattern;
示例
示例使用 RUNOOB 样本数据库。
该库包含有 "Websites" 表:
+----+--------------+---------------------------+-------+---------+
| id | name | url | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1 | Google | https://www.google.cm/ | 1 | USA |
| 2 | 淘宝 | https://www.taobao.com/ | 13 | CN |
| 3 | 菜鸟教程 | http://www.runoob.com/ | 4689 | CN |
| 4 | 微博 | http://weibo.com/ | 20 | CN |
| 5 | Facebook | https://www.facebook.com/ | 3 | USA |
| 7 | stackoverflow | http://stackoverflow.com/ | 0 | IND |
+----+---------------+---------------------------+-------+---------+
选取 name 以字母 "G" 开始的所有客户:
SELECT * FROM Websites
WHERE name LIKE 'G%';
执行输出结果:
mysql> SELECT * FROM Websites
-> WHERE name LIKE 'G%';
+----+--------------+---------------------------+-------+---------+
| id | name | url | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1 | Google | https://www.google.cm/ | 1 | USA |
+----+---------------+---------------------------+-------+---------+
提示: "%" 符号用于在模式的前后定义通配符(缺省字母)。
选取 name 以字母 "k" 结尾的所有客户:
SELECT * FROM Websites
WHERE name LIKE '%k';
执行输出结果:
mysql> SELECT * FROM Websites
-> WHERE name LIKE '%k';
+----+--------------+---------------------------+-------+---------+
| id | name | url | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 5 | Facebook | https://www.facebook.com/ | 3 | USA |
+----+---------------+---------------------------+-------+---------+
选取 name 包含模式 "oo" 的所有客户:
SELECT * FROM Websites
WHERE name LIKE '%oo%';
执行输出结果:
mysql> SELECT * FROM Websites
-> WHERE name LIKE '%oo%';
+----+--------------+---------------------------+-------+---------+
| id | name | url | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 1 | Google | https://www.google.cm/ | 1 | USA |
| 5 | Facebook | https://www.facebook.com/ | 3 | USA |
+----+---------------+---------------------------+-------+---------+
使用 NOT 关键字,可以选取不匹配模式的记录。
选取 name 不包含模式 "oo" 的所有客户:
SELECT * FROM Websites
WHERE name NOT LIKE '%oo%';
输出结果:
mysql> SELECT * FROM Websites
-> WHERE name NOT LIKE '%oo%';
+----+--------------+---------------------------+-------+---------+
| id | name | url | alexa | country |
+----+--------------+---------------------------+-------+---------+
| 2 | 淘宝 | https://www.taobao.com/ | 13 | CN |
| 3 | 菜鸟教程 | http://www.runoob.com/ | 4689 | CN |
| 4 | 微博 | http://weibo.com/ | 20 | CN |
| 7 | stackoverflow | http://stackoverflow.com/ | 0 | IND |
+----+---------------+---------------------------+-------+---------+
更多
字符串 | 描述 |
---|---|
%a' | 以 a 结尾的数据 |
'a%' | 以 a 开头的数据 |
'%a%' | 含有 a 的数据 |
'a' | 三位且中间字母是 a 的 |
'_a' | 两位且结尾字母是 a 的 |
'a_' | 两位且开头字母是 a 的 |